package cfca.paperless.client.servlet._8_local.suning;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.io.FileUtils;

import cfca.paperless.client.bean.MultiDataBean;
import cfca.paperless.client.bean.ProofUserInfo;
import cfca.paperless.client.bean.SignLocation;
import cfca.paperless.client.servlet.PaperlessClient;
import cfca.paperless.client.servlet.PaperlessClientLocal;
import cfca.paperless.client.servlet.PaperlessLocalConfig;
import cfca.paperless.client.servlet.tools.ProofHashUtil;
import cfca.paperless.client.util.IoUtil;
import cfca.paperless.client.util.PdfUtil;
import cfca.paperless.client.util.StringUtil;
import cfca.sadk.x509.certificate.X509Cert;


/**
 * <pre>
 * Modify Information:
 * Author       Date          Description
 * ============ ============= ============================
 * zf           2018年4月8日         申请下载场景证书、签场景章、签普通企业章
 * </pre>
 */
public class CompoundSealAutoPdfLocalTest02 {
 
    public static void main(String[] args) throws Exception {
        try {
            long timeStart = System.currentTimeMillis();// 开始时间
            
            // 印章图片显示效果用的参数，根据实际需求调整此参数大小 
            float coefficient = 1f;
            
            // 无纸化辅助接口的访问URL
            PaperlessClient clientExtBean = new PaperlessClient(PaperlessLocalConfig.extUrl, 10000, 60000);
            // 无纸化辅助接口的访问URL
            PaperlessClient clientAssistBean = new PaperlessClient(PaperlessLocalConfig.assistUrl, 10000, 60000);

            PaperlessClientLocal paperlessClientLocal = new PaperlessClientLocal(clientExtBean, clientAssistBean, PaperlessLocalConfig.operatorCode);
            //设置时间戳 
            paperlessClientLocal.initTimestampServer(PaperlessLocalConfig.timeServerUrl, "", "");
       
            
            // 待签章pdf
            String filePath = "./TestData/file.pdf";
            byte[] pdf = FileUtils.readFileToByteArray(new File(filePath));
            
            // 印模图片
            byte[] handwritingImage = FileUtils.readFileToByteArray(new File("./TestData/seal.png"));
       
            //计算证据hash 
            String proofHashXml = getProofHashXml(handwritingImage);
            
            // 合成proofHash 到pdf附件 proofHash.xml 中 
            pdf = PdfUtil.compoundPdfDataByAttachment(pdf, proofHashXml.getBytes(), "proofHash.xml");
   
            //申请场景证书要素
            ProofUserInfo proofUserInfo = generateProofUserInfo(proofHashXml);
          
            /* 申请下载场景证书 */
            String result = paperlessClientLocal.applyAndDownloadCert(proofUserInfo);
            X509Cert x509Cert = null;
            String code = StringUtil.getNodeText(result, "Code");
            // 返回值Code等于200代表后台处理成功
            if (code.equals("200")) {
                String certData = StringUtil.getXmlField(result, "Cert");
                x509Cert = new X509Cert(certData.getBytes());
            } else {
                String signMessage = StringUtil.getNodeText(result, "Message");
                throw new Exception(signMessage);
            }
            
            // 签名位置 坐标签章
            SignLocation signLocation = new SignLocation(1, 200, 200);
            
            //签章杂项信息
            paperlessClientLocal.initSealInfo("张三", "签合同", "北京亦庄");
            
            
            // 3-指定需要显示的文本内容（如用户姓名）
            String sealLayer2Text = "张三";// 印章显示为文本内容（如用户姓名），可以为空，不为空时此文本会替代上面的图片
            String sealLayer2TextStyle = "font-size:10;font-color:FF0000;width:100;";// 文本显示样式（文字大小、文字颜色、显示总宽度），可以为空
            //场景证书签章 签文本
            byte[] sealedPdfData = paperlessClientLocal.sealAutoPdfProofLocal(pdf, x509Cert,sealLayer2Text,sealLayer2TextStyle, signLocation);
            
            //场景证书签章 签图片
            //byte[] sealedPdfData = paperlessClientLocal.sealAutoPdfProofLocal(pdf, x509Cert, privateKey, handwritingImage, coefficient, signLocation);
      
            //印章编码 印章密码
            String sealCode = "yz201804847655019";
            String sealPassword ="cfca1234";
            
            //签章位置 坐标签章
            signLocation = new SignLocation(1,100,100);
            
            //签普通企业章
            sealedPdfData = paperlessClientLocal.sealAutoPdfLocal(sealedPdfData, sealCode, sealPassword, coefficient,signLocation);
            
            
            String outputFilePath = "./TestData/output/signAutoPdf02.pdf";
            System.out.println("pdfSealVerifier ok " + outputFilePath);
            IoUtil.write(outputFilePath, sealedPdfData);
            
            
            long timeEnd = System.currentTimeMillis();// 结束时间
            System.out.println("time:" + (timeEnd - timeStart));

        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    
    /**
     * <p>Description 计算证据 proofHash </p>
     * @author zf
     * @date 2018年4月9日 下午2:49:36
     * @param handwritingImage
     * @return
     * @throws Exception
     */
    private static String getProofHashXml(byte[] handwritingImage) throws Exception{
        
        byte[] identificationFrontData = FileUtils.readFileToByteArray(new File("./TestData/1.png"));
        byte[] identificationBackData = FileUtils.readFileToByteArray(new File("./TestData/2.png"));
        List<MultiDataBean> list = new ArrayList<MultiDataBean>();
        list.add(new MultiDataBean(handwritingImage, "handwritingImage.png", "0"));// 手写签名图片
        list.add(new MultiDataBean(identificationFrontData, "identificationFrontImage.png", "0"));// 身份证正面
        list.add(new MultiDataBean(identificationBackData, "identificationBackImage.png", "0"));// 身份证反面

        // 计算proofHash
        return ProofHashUtil.getProofHashXml(list);
        
         
    }

    /**
     * <p>Description 申请场景证书要素 </p>
     * @author zf
     * @date 2018年4月9日 下午2:50:04
     * @param selfExtValue
     * @return
     */
    private static ProofUserInfo generateProofUserInfo(String selfExtValue){
        
        /* 申请场景证书 要素  */
        String userName = "张珊珊";
        String identificationType = "0";
        String identificationNo = "454212556565656";
        String keyAlg = "RSA";
        int keyLength = 2048;
        return  new ProofUserInfo(userName, identificationType, identificationNo, keyAlg, keyLength, selfExtValue);
    }
 
}
